<?php

namespace App\Request\auth\Service\Common;

use Hyperf\HttpMessage\Upload\UploadedFile;
use League\Flysystem\Filesystem;
use League\Flysystem\FilesystemException;
use function Hyperf\Config\config;

/**
 * 文件上传服务
 */
class UploadService
{

    public function __construct(
        protected readonly Filesystem $filesystem,
    )
    {
    }

    /**
     * 文件上传
     * @return string[]
     * @throws FilesystemException
     */
    function uploadFile(UploadedFile $file): array
    {
        // 获取文件扩展名
        $extension = $file->getClientFilename() ? pathinfo($file->getClientFilename(), PATHINFO_EXTENSION) : 'txt';

        // 构建日期目录路径
        $datePath = date('Ymd');

        // 生成唯一文件名
        $filename = uniqid('', true) . '.' . $extension;

        // 完整路径
        $path = "uploads/{$datePath}/{$filename}";

        // 容器里实际路径
        $fullDir = BASE_PATH . "/storage/uploads/{$datePath}";
        $fullPath = $fullDir . '/' . $filename;

        // 确保目录存在
        if (!is_dir($fullDir)) {
            mkdir($fullDir, 0777, true);  // 创建目录并设置权限
            chmod($fullDir, 0777);
        }

        // 获取文件内容流
        $stream = $file->getStream()->getContents();
        // 写入文件
//        $this->filesystem->write($fullPath, $stream);
        file_put_contents($fullPath, $stream);
        // 写入后设置文件权限
        if (file_exists($fullPath)) {
            chmod($fullPath, 0777);
        }

        // 返回完整 URL
        return [
            'url' => config("upload_cdn") . '/' . $path,
            'path' => $path,
        ];
    }

}